import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { config } from './config'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    meta: {
      auth: false,
    },
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/layout',
    name: 'layout',
    component: () => import('../layouts/index.vue'),
    children: [
      {
        path: 'home',
        name: 'home',
        meta: {
          roles: ['admin', 'editor'],
          auth: true,
        },
        component: () => import('../views/HomeView.vue'),
      },
      {
        path: 'register',
        name: 'register',
        meta: {
          roles: ['admin', 'editor'],
          auth: true,
        },
        component: () => import('../views/Register.vue'),
      },
      {
        path: 'blogs',
        name: 'blogs',
        meta: {
          roles: ['admin', 'editor'],
          auth: true,
        },
        component: () => import('../views/BlogsPage.vue'),
      },
      {
        path: 'users',
        name: 'users',
        meta: {
          roles: ['admin'],
          auth: true,
        },
        component: () => import('../views/Users.vue'),
      },
      {
        path: 'echarts',
        name: 'echarts',
        meta: {
          roles: ['admin'],
          auth: true,
        },
        component: () => import('../views/Echarts.vue'),
      },
      {
        path: 'code',
        name: 'code',
        meta: {
          roles: ['admin'],
          auth: true,
        },
        component: () => import('../views/CodePage.vue'),
      },
    ],
  },
]

const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch((err) => err)
}

//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch((err) => err)
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

router.beforeEach((to, from, next) => {
  if (to.meta.auth) {
    const token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          fullpath: to.fullPath,
        },
      })
    }
  } else {
    next()
  }
})

export default router
